namespace devtm.Aop.Emit
{
    using System;
    using Mono.Cecil;
    using Mono.Cecil.Cil;
    using devtm.Aop.Extensions;

    [Serializable]
    public class EmitArgumentReferenceExpression : EmitExpression
    {

        private int typeParameter = 0;
        private string parameterName;
        private ParameterDefinition _parameter;


        public EmitArgumentReferenceExpression(string parameterName)
        {
            this.parameterName = parameterName;
            typeParameter = 1;
        }

        public EmitArgumentReferenceExpression(int index)
        {
            this.Index = index;
            typeParameter = 2;
        }

        public string ParameterName
        {
            get
            {
                if (this.parameterName != null)
                {
                    return this.parameterName;
                }
                return string.Empty;
            }
            set
            {
                this.parameterName = value;
            }
        }

        public int Index { get; set; }

        public override void Compile(CilWorker gen)
        {


                foreach (ParameterDefinition item in gen.Body.Method.Parameters)
                {
                    if (typeParameter == 1)
                    {
                        if (item.Name == parameterName)
                            _parameter = item;
                    }
                    else
                    {
                        if (item.Index == this.Index)
                            _parameter = item;
                    }

                }


                gen.WriteParameterArgument(_parameter);

        }

        
    }
}
